package com.dongdongshop.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dongdongshop.constant.OssConstant;
import com.dongdongshop.result.Result;
import com.dongdongshop.result.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("oss")
public class OSSController {

    private static final Logger logger = LoggerFactory.getLogger(OSSController.class);

    @RequestMapping("upload")
    @ResponseBody
    public Result upload(@RequestParam("myFile") MultipartFile myFile){
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "http://"+ OssConstant.END_POINT;
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = OssConstant.ACCESS_KEY_ID;
        String accessKeySecret = OssConstant.ACCESS_KEY_SECRET;

        String bucketName = OssConstant.BUCKET_NAME;
        String objectName = "dongdongshop/" + UUID.randomUUID() + myFile.getOriginalFilename();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String url = "http://"+bucketName+"."+ OssConstant.END_POINT +"/"+objectName;

        //上传内到指定的存储空间(bucketName)  并保存为指定的文件名称(objectName)
        try {
            ossClient.putObject(bucketName, objectName, myFile.getInputStream());
        } catch (IOException e) {
            logger.error("系统报错",e);
        }

        // 关闭OSSClient。
        ossClient.shutdown();
        return Result.jsonResponse(ResultEnum.OK).setData(url );
    }
}
